<template>
  <div class="user-behavior-page">
    <el-card>
      <template #header>
        <div class="header-bar">
          <span>用户行为分析</span>
          <el-button size="small" type="primary" @click="simulateUserAction">模拟一次用户操作</el-button>
          <el-button size="small" @click="clearLogs">清空日志</el-button>
          <el-button size="small" type="success" @click="exportLogs">导出日志</el-button>
        </div>
      </template>

      <el-row :gutter="20">
        <el-col :span="14">
          <el-card>
            <div class="chart-title">点击频率排行</div>
            <div ref="hotChart" class="chart-container" />
          </el-card>
        </el-col>
        <el-col :span="10">
          <el-card>
            <div class="chart-title">用户行为日志</div>
            <el-scrollbar max-height="280px">
              <el-timeline>
                <el-timeline-item v-for="(log, index) in logs" :key="index" :timestamp="log.time">
                  {{ log.action }}
                </el-timeline-item>
              </el-timeline>
            </el-scrollbar>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-top: 20px;">
        <el-col :span="12">
          <el-card>
            <div class="chart-title">用户画像（模块偏好）</div>
            <div ref="portraitChart" class="chart-container" />
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card>
            <div class="chart-title">模块停留时长（秒）</div>
            <div ref="stayChart" class="chart-container" />
          </el-card>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import dayjs from 'dayjs'
import * as echarts from 'echarts'
import { saveAs } from 'file-saver'

const logs = ref([])
const actionFrequency = ref({})
const moduleStayTime = ref({})

// 模拟模块池
const actions = [
  '进入 数据引擎',
  '新增 数据源',
  '查看 模型管理',
  '导出 模型报告',
  '切换 饼图',
  '编辑 字段元数据',
  '进入 模板管理',
  '删除 模板',
  '打印 图表',
  '查看 用户行为'
]

// 图表 ref
const hotChart = ref(null)
const portraitChart = ref(null)
const stayChart = ref(null)

function simulateUserAction() {
  const action = actions[Math.floor(Math.random() * actions.length)]
  const time = dayjs().format('HH:mm:ss')
  logs.value.unshift({ action, time })

  // 点击频率
  if (!actionFrequency.value[action]) {
    actionFrequency.value[action] = 1
  } else {
    actionFrequency.value[action] += 1
  }

  // 模拟停留时长（增加 2~10 秒）
  const mod = action.split(' ')[1]
  if (!moduleStayTime.value[mod]) {
    moduleStayTime.value[mod] = Math.floor(Math.random() * 8 + 2)
  } else {
    moduleStayTime.value[mod] += Math.floor(Math.random() * 5 + 1)
  }

  renderAllCharts()
}

function clearLogs() {
  logs.value = []
  actionFrequency.value = {}
  moduleStayTime.value = {}
  renderAllCharts()
}

function exportLogs() {
  const content = logs.value.map(l => `[${l.time}] ${l.action}`).join('\\n')
  const blob = new Blob([content], { type: 'text/plain;charset=utf-8' })
  saveAs(blob, '用户行为日志.txt')
}

function renderAllCharts() {
  renderHotChart()
  renderPortraitChart()
  renderStayChart()
}

function renderHotChart() {
  const inst = echarts.init(hotChart.value)
  const data = Object.entries(actionFrequency.value).map(([name, val]) => ({ name, value: val }))
  data.sort((a, b) => b.value - a.value)
  inst.setOption({
    title: { text: '模块点击频率', left: 'center' },
    xAxis: { type: 'category', data: data.map(d => d.name), axisLabel: { rotate: 30 } },
    yAxis: {},
    series: [{ type: 'bar', data: data.map(d => d.value), itemStyle: { color: '#1890FF' } }]
  })
}

function renderPortraitChart() {
  const inst = echarts.init(portraitChart.value)
  const raw = Object.entries(actionFrequency.value)
  const moduleMap = {}
  raw.forEach(([action, count]) => {
    const mod = action.split(' ')[1]
    moduleMap[mod] = (moduleMap[mod] || 0) + count
  })
  const data = Object.entries(moduleMap).map(([name, val]) => ({ name, value: val }))
  inst.setOption({
    title: { text: '偏好分布', left: 'center' },
    tooltip: { trigger: 'item' },
    series: [{
      type: 'pie',
      radius: ['40%', '70%'],
      data,
      label: { formatter: '{b}: {d}%' }
    }]
  })
}

function renderStayChart() {
  const inst = echarts.init(stayChart.value)
  const data = Object.entries(moduleStayTime.value).map(([mod, sec]) => ({ name: mod, value: sec }))
  inst.setOption({
    title: { text: '模块停留时长', left: 'center' },
    xAxis: { type: 'category', data: data.map(d => d.name) },
    yAxis: { type: 'value', name: '秒' },
    series: [{
      type: 'line',
      data: data.map(d => d.value),
      lineStyle: { color: '#fa541c' },
      smooth: true
    }]
  })
}

onMounted(() => {
  nextTick(() => {
    for (let i = 0; i < 4; i++) {
      simulateUserAction()
    }
  })
})

</script>

<style scoped>
.user-behavior-page {
  padding: 10px;
}
.header-bar {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}
.chart-container {
  width: 100%;
  height: 280px;
}
.chart-title {
  font-weight: bold;
  margin-bottom: 10px;
}
</style>
